package stopthread;

/**
 * @description:
 * @author: jhy
 * @time: 2021/4/11 23:08
 */
public class UseFlagStopThread {

    public static void main(String[] args) throws InterruptedException {
        MyThread4 m1 = new MyThread4();
        System.out.println("Starting thread...");
        m1.start();
        Thread.sleep(3000);
        System.out.println("Interrupt thread...: " + m1.getName());
        // 设置共享变量为true,使得m1线程停止
        m1.stop = true; ;
    }


}

class MyThread4 extends Thread {
    //volatile保证该变量的可见性，该变量被其他线程修改，可以立刻被其他线程看到
    volatile boolean stop = false;

    public void run() {
        while (!stop) {
            System.out.println(getName() + " is running");
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("week up from blcok...");
                stop = true; // 在异常处理代码中修改共享变量的状态
            }
        }
    }
}